"""Redis缓存配置模块"""

import redis
import json
import logging
from typing import Optional, Any, Dict, List
from datetime import timedelta
from .settings import api_settings

logger = logging.getLogger(__name__)


class RedisManager:
    """Redis连接管理器"""
    
    def __init__(self):
        self.redis_client: Optional[redis.Redis] = None
        self.enabled = api_settings.REDIS_ENABLED
        self._initialize_connection()
    
    def _initialize_connection(self):
        """初始化Redis连接"""
        if not self.enabled:
            logger.info("🔴 [Redis] Redis缓存已禁用")
            return
            
        try:
            self.redis_client = redis.Redis(
                host=api_settings.REDIS_HOST,
                port=api_settings.REDIS_PORT,
                password=api_settings.REDIS_PASSWORD if api_settings.REDIS_PASSWORD else None,
                db=api_settings.REDIS_DB,
                decode_responses=True,  # 自动解码响应
                socket_connect_timeout=5,
                socket_timeout=5,
                retry_on_timeout=True,
                health_check_interval=30
            )
            
            # 测试连接
            self.redis_client.ping()
            logger.info("✅ [Redis] Redis连接成功")
            
        except Exception as e:
            logger.warning(f"⚠️ [Redis] Redis连接失败，将禁用缓存功能: {e}")
            self.redis_client = None
            self.enabled = False
    
    def is_available(self) -> bool:
        """检查Redis是否可用"""
        if not self.enabled or not self.redis_client:
            return False
            
        try:
            self.redis_client.ping()
            return True
        except Exception:
            return False
    
    def set(self, key: str, value: Any, expire: Optional[int] = None) -> bool:
        """设置缓存"""
        if not self.is_available():
            return False
            
        try:
            # 序列化值
            if isinstance(value, (dict, list)):
                value = json.dumps(value, ensure_ascii=False)
            elif not isinstance(value, str):
                value = str(value)
            
            # 设置缓存
            result = self.redis_client.set(key, value, ex=expire)
            logger.debug(f"📝 [Redis] 设置缓存: {key}")
            return result
            
        except Exception as e:
            logger.error(f"❌ [Redis] 设置缓存失败 {key}: {e}")
            return False
    
    def get(self, key: str) -> Optional[Any]:
        """获取缓存"""
        if not self.is_available():
            return None
            
        try:
            value = self.redis_client.get(key)
            if value is None:
                return None
            
            # 尝试反序列化JSON
            try:
                return json.loads(value)
            except (json.JSONDecodeError, TypeError):
                return value
                
        except Exception as e:
            logger.error(f"❌ [Redis] 获取缓存失败 {key}: {e}")
            return None
    
    def delete(self, key: str) -> bool:
        """删除缓存"""
        if not self.is_available():
            return False
            
        try:
            result = self.redis_client.delete(key)
            logger.debug(f"🗑️ [Redis] 删除缓存: {key}")
            return bool(result)
            
        except Exception as e:
            logger.error(f"❌ [Redis] 删除缓存失败 {key}: {e}")
            return False
    
    def exists(self, key: str) -> bool:
        """检查缓存是否存在"""
        if not self.is_available():
            return False
            
        try:
            return bool(self.redis_client.exists(key))
        except Exception as e:
            logger.error(f"❌ [Redis] 检查缓存存在性失败 {key}: {e}")
            return False
    
    def expire(self, key: str, seconds: int) -> bool:
        """设置缓存过期时间"""
        if not self.is_available():
            return False
            
        try:
            return bool(self.redis_client.expire(key, seconds))
        except Exception as e:
            logger.error(f"❌ [Redis] 设置过期时间失败 {key}: {e}")
            return False
    
    def keys(self, pattern: str = "*") -> List[str]:
        """获取匹配的键列表"""
        if not self.is_available():
            return []
            
        try:
            return self.redis_client.keys(pattern)
        except Exception as e:
            logger.error(f"❌ [Redis] 获取键列表失败 {pattern}: {e}")
            return []
    
    def flushdb(self) -> bool:
        """清空当前数据库"""
        if not self.is_available():
            return False
            
        try:
            self.redis_client.flushdb()
            logger.info("🧹 [Redis] 数据库已清空")
            return True
        except Exception as e:
            logger.error(f"❌ [Redis] 清空数据库失败: {e}")
            return False
    
    def get_info(self) -> Dict[str, Any]:
        """获取Redis信息"""
        if not self.is_available():
            return {"status": "disabled"}
            
        try:
            info = self.redis_client.info()
            return {
                "status": "connected",
                "version": info.get("redis_version"),
                "used_memory": info.get("used_memory_human"),
                "connected_clients": info.get("connected_clients"),
                "total_commands_processed": info.get("total_commands_processed")
            }
        except Exception as e:
            logger.error(f"❌ [Redis] 获取信息失败: {e}")
            return {"status": "error", "error": str(e)}


# 创建全局Redis管理器实例
redis_manager = RedisManager()


# 便捷函数
def get_redis() -> RedisManager:
    """获取Redis管理器实例"""
    return redis_manager


def cache_set(key: str, value: Any, expire: Optional[int] = None) -> bool:
    """设置缓存的便捷函数"""
    return redis_manager.set(key, value, expire)


def cache_get(key: str) -> Optional[Any]:
    """获取缓存的便捷函数"""
    return redis_manager.get(key)


def cache_delete(key: str) -> bool:
    """删除缓存的便捷函数"""
    return redis_manager.delete(key)


def cache_exists(key: str) -> bool:
    """检查缓存存在的便捷函数"""
    return redis_manager.exists(key)
